package com.soft.collateral.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/7/23
 */
public class JwtHelper {

    //设置访问令牌有效期 2h
    private static long tokenExpiration = 2*60*60*1000;
    //设置刷新令牌有效期 3*24h
    private static long refreshTokenExpiration = 3*24*60*60*1000;

    //秘钥
    private static String tokenSignKey = "com.geek.health.aGVhbHRoMTIz";

    //生成Token访问令牌
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("HEALTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //生成Token刷新令牌
    public static String createRefreshToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("HEALTH-USER")
                .setExpiration(new Date(System.currentTimeMillis() + refreshTokenExpiration))
                .claim("userId", userId)
                .claim("userName", userName)
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }

    //刷新Token
    public static String refreshToken(String token) {
        String refreshedToken;
        try {
            // 解析原始令牌，获取令牌中的声明
            final Claims claims = Jwts.parser()
                    .setSigningKey(tokenSignKey)
                    .parseClaimsJws(token)
                    .getBody();
            //使用原始令牌中的信息创建一个新的令牌
            refreshedToken = JwtHelper.createRefreshToken(getUserId(token), getUserName(token));
        } catch (Exception e) {
            // 发生异常时，将刷新令牌设置为null
            refreshedToken = null;
        }
        return refreshedToken;
    }

    //通过token获取用户ID
    public static Long getUserId(String token) {
        if(StringUtils.hasLength(token)){
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            Integer userId = (Integer)claims.get("userId");
            return userId.longValue();
        }
        return null;
    }

    //通过token获取用户姓名
    public static String getUserName(String token) {
        if(StringUtils.hasLength(token)){
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
            Claims claims = claimsJws.getBody();
            return (String)claims.get("userName");
        }
        return null;
    }

    //判断token是否有效
    public static boolean isExpiration(String token) {
        try {
            boolean isExpire = Jwts.parser()
                    .setSigningKey(tokenSignKey)
                    .parseClaimsJws(token)
                    .getBody()
                    .getExpiration().before(new Date());
            //没有过期，有效，返回false
            return isExpire;
        } catch (Exception e) {
            //过期出现异常，返回true
            return true;
        }
    }

    public static long getTokenExpiration() {
        return tokenExpiration;
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(2L, "李四");
        //eyJhbGciOiJIUzUxMiIsInppcCI6IkdaSVAifQ.H4sIAAAAAAAAAKtWKi5NUrJScvL3D9ENDXYNUtJRSq0oULIyNDexNDE3Nzcz1VEqLU4t8kxRsjKCMP0Sc1OBWp7N7Xs6e7ZSLQCkMCnHQwAAAA.k1k-SedXIYLFQP05cHUadjgvKDcIb-RcuL2rir7SO0RwtfcHr0lmoggZCB53u0AYaJLpgH65ziJIW1o7x2tK2A
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUserName(token));
    }

}
